package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.constant.BspsTreeNodeConstant;
import cc.rengu.igas.bsps.common.enums.MchntTypeEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.ReconDetailDownloadRequest;
import cc.rengu.igas.bsps.facade.response.ReconDetailDownloadResponse;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;

/**
 * 对账单下载服务
 * Created by 王成 on 2018/6/13.
 */
public class ReconDetailDownloadService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        ReconDetailDownloadRequest reconDetailDownloadRequest = new ReconDetailDownloadRequest();
        ConvertUtil.convertOutput(reconDetailDownloadRequest);
        return reconDetailDownloadRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        ReconDetailDownloadRequest reconDetailDownloadRequest = (ReconDetailDownloadRequest) request;
        ReconDetailDownloadResponse reconDetailDownloadResponse = new ReconDetailDownloadResponse();
        /* 参数合法性检查 */
        if (StringUtil.isEmptyOrNull(reconDetailDownloadRequest.getMchntNo()) || StringUtil.isEmptyOrNull(reconDetailDownloadRequest.getSettleDate())) {
            rglog.error("请求参数商户号<{}>及清算日期<{}>不能为空!", reconDetailDownloadRequest.getMchntNo(), reconDetailDownloadRequest.getSettleDate());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        /* 获取对账文件存储路径：根目录/CMSC/RECON/法人行/对账日期/商户号/商户对账文件*/
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID, BspsAppParamConstant.FILE_PATH_PARAM, BspsAppParamConstant.MCHNT_RECON_FILE_PATH);
        if (sysParam == null) {
            rglog.info("文件存储路径未配置");
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        //2021/01/07 确认需求,文件清算日期是前一天的
        String fileSettleDate = DateUtil.getBaseDateOffsetDay(reconDetailDownloadRequest.getSettleDate(), -1);

        //String filePath = "/epaydata/csmc/file/RECON";
        String filePath = sysParam.getParamValue();
        filePath = filePath + File.separator + reconDetailDownloadRequest.getHeader().getInstId() + File.separator + fileSettleDate + File.separator;
        String fileName = "epay_".concat(reconDetailDownloadRequest.getMchntNo()).concat("_").concat(fileSettleDate).concat(".csv");

        if (reconDetailDownloadRequest.getMchntNo().startsWith("AG")) {
            //代理商商户
            filePath = filePath + "AMRECRSLF";
        } else if (reconDetailDownloadRequest.getMchntNo().startsWith("PM")) {
            //平台商户
            filePath = filePath + "PMRECRSLF";
        } else {
            //普通商户
            filePath = filePath + "MRECRSLF";
            MchntService mchntService = new MchntServiceImpl();
            MchntInfo mchntInfo = mchntService.getMchntInfo(reconDetailDownloadRequest.getHeader().getInstId(), reconDetailDownloadRequest.getMchntNo());
            if (null == mchntInfo) {
                rglog.error("获取商户信息失败,mchntNo:<{}>", reconDetailDownloadRequest.getMchntNo());
                throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
            }
            if (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(mchntInfo.getMchntType())) {
                if (AppParamConstant.NO.equals(mchntInfo.getIndependentDataFlag())) {
                    throw new BizException(RespCodeEnum.CHAIN_STORE_NOT_INDEPENDENT_CANNOT_OPERATE.getRespCode(), RespCodeEnum.CHAIN_STORE_NOT_INDEPENDENT_CANNOT_OPERATE.getRespDesc());
                }
                fileName = "epay_".concat(mchntInfo.getChainMchntNo()).concat("_").concat(mchntInfo.getMchntNo()).concat("_").concat(fileSettleDate).concat(".csv");
            }
        }

        rglog.debug("================目录" + filePath);
        rglog.debug("================欲下载名称" + fileName);
        File reconFile = new File(filePath);
        if (!reconFile.exists()) {
            rglog.error("目录不存在.");
            throw new BizException(RespCodeEnum.FILE_NOT_EXIST.getRespCode(), RespCodeEnum.FILE_NOT_EXIST.getRespDesc());
        }

        String reconDetailPath = filePath + File.separator + fileName;
        File reconDetailFile = new File(reconDetailPath);
        if (!reconDetailFile.exists()) {
            rglog.error("文件<{}>不存在.", reconDetailPath);
            throw new BizException(RespCodeEnum.FILE_NOT_EXIST.getRespCode(), RespCodeEnum.FILE_NOT_EXIST.getRespDesc());
        }

        BizResponse bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        reconDetailDownloadResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        reconDetailDownloadResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(reconDetailDownloadResponse);

        /*IE8特殊处理*/
        if ("Y".equals(xmlTreeUtil.getXmlTreeStringValue(BspsTreeNodeConstant.IS_GET_REQUEST))) {
            xmlTreeUtil.setXmlTreeStringValue(BspsTreeNodeConstant.RECON_DETAIL_PATH, reconDetailPath);
            return bizResponse;
        }

        /*正常处理,读文件*/
        byte[] fileBytes = null;
        //IO流操作
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(reconDetailFile);
            fileBytes = new byte[fileInputStream.available()];
            fileInputStream.read(fileBytes);
        } catch (Exception e) {
            rglog.error(e.getMessage());
        } finally {
            //关闭流
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            } catch (Exception e) {
                rglog.error(e.getMessage());
            }
        }

        /* 组装应答信息 */
        ConvertUtil.convertOutput(reconDetailDownloadResponse);
        reconDetailDownloadResponse.setFileName(fileName);
        if (null != fileBytes) {
            reconDetailDownloadResponse.setFileContent(Base64.encodeBase64String(fileBytes));
        }
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        ReconDetailDownloadResponse reconDetailDownloadResponse = (ReconDetailDownloadResponse) bizResponse.getResult();
        ConvertUtil.convertInput(reconDetailDownloadResponse);
    }

}
